package com.roc.web.action.terminal;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.YjPosInfo;
import com.roc.service.IExcelExportService;
import com.roc.service.IMerchantServices;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.DateUtil;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.util.constant.Terminal;

@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/terminal")
public class TermSnRevocationAction extends PaginationBaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	static Logger logger = LogManager.getLogger(TermSnRevocationAction.class);

	private Long psamCardStartNo;
	private Long psamCardEndNo;
	private Long totalNum;
	private TermSnRevocationSearchCondition searchCondition;

	private List<TblInsInf> orgList = new ArrayList<TblInsInf>();

	private InputStream excelFile;
	private String excelName;

	@Autowired
	IPageService pagenitionService;

	@Autowired
	private IorgService orgService;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired
	ITerminalService terminalService;
	
	private String serialnums; // sn 数组

	@Action(value = "termRevocationInit", results = { @Result(location = "/pages/terminal/termSnRevocation.jsp") })
	public String termRevocationInit() throws Exception {
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if( !op.getRoleType().equals(Role.SYSTEM.getCode()) 
				&& !op.getRoleType().equals(Role.O_MANAGER.getCode())
				&& !op.getRoleType().equals(Role.AGENT.getCode())
				&& !op.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode()) 
				&& !op.getRoleType().equals(Role.OPERATORS_LEAD.getCode()) ){
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		org();
		return SUCCESS;
	}

	@Action(value = "queryRevocationTerminalPosSN", results = { @Result(name = "success", location = "/pages/terminal/termSnRevocation.jsp") })
	// 查询终端
	public String queryRevocationTerminalPosSN() throws Exception {

		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if (searchCondition == null) {
			searchCondition = (TermSnRevocationSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new TermSnRevocationSearchCondition();
			}
		}
		try {
			if( !op.getRoleType().equals(Role.SYSTEM.getCode()) 
					&& !op.getRoleType().equals(Role.O_MANAGER.getCode())
					&& !op.getRoleType().equals(Role.AGENT.getCode())
					&& !op.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode()) 
					&& !op.getRoleType().equals(Role.OPERATORS_LEAD.getCode()) ){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			org();

			searchCondition.setOpRoleType(op.getRoleType());
			searchCondition.setAccountId(op.getId());
			
			int rows = pagenitionService.countSQL(searchCondition);

			searchRsList = pagenitionService.findAllSQL(searchCondition,
					calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);

			List<YjPosInfo> posList = new ArrayList<YjPosInfo>();
			if (searchRsList != null && searchRsList.size() > 0) {
				Iterator iterator = searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();
					YjPosInfo pos = new YjPosInfo();
					pos.setSerialNum(Constance.Null2EmptyTrim(obj[0]));

					String brandCode = obj[1] + "";
					String typeCode = obj[2] + "";
					String nameCode = obj[3] + "";
					
					pos.setPosBrand(ConfigMerinfoUtil.getPosBRAND(brandCode));
					pos.setPosName(ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode));
					pos.setPosType(ConfigMerinfoUtil.getTerminalType(typeCode));
					
					pos.setOrgCode(Constance.Null2EmptyTrim(obj[4]));
					pos.setIsBind(Terminal.valueOfCode(
							Constance.Null2EmptyTrim(obj[5])).getName());
				/*	pos.setIsUsed(Terminal.valueOfCode(
							Constance.Null2EmptyTrim(obj[6])).getName());*/
					pos.setMercCode(Constance.Null2EmptyTrim(obj[6]));
					pos.setTermCode(Constance.Null2EmptyTrim(obj[7]));
					pos.setRemark(Constance.Null2EmptyTrim(obj[8]));
					pos.setInDateStr(DateUtil.formatTime(Constance
							.Null2EmptyTrim(obj[9])));
					pos.setOutDateStr(DateUtil.formatTime(Constance
							.Null2EmptyTrim(obj[10])));
					pos.setAgentName(Constance.Null2EmptyTrim(obj[11]));
					pos.setOperators(Constance.Null2EmptyTrim(obj[12]));
					// 厂商编号
					pos.setPosBrandCode(brandCode);
					if ( !"".equals( Constance.Null2EmptyTrim(obj[13]) ) ){
						pos.setTekId(Terminal.valueOfCode(
								Constance.Null2EmptyTrim(obj[13])).getName());
					}
					posList.add(pos);
				}
			}
			searchRsList.clear();
			searchRsList.addAll(posList);
			dealWithTheListSpecially(searchRsList);
			getRequest().setAttribute("posList", posList);
/*			getRequest().setAttribute("agenid", searchCondition.getAgentId());*/
			getRequest().setAttribute("selModelCode", searchCondition.getPosName());
			getRequest().setAttribute("oldBandCode", searchCondition.getPosBrand());
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}

		return SUCCESS;
	}

	private void org() {
		Operators loginOperator = (Operators) ActionContext.getContext()
				.getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		try {
			TblInsInf inf = new TblInsInf();
			orgList=orgService.listOrg(inf);

			getRequest().setAttribute("brandMap",ConfigProperties.getSysDB1("TMNL_BRAND",true));
			getRequest().setAttribute("nameMap", new ArrayList<Map<String,Object>>());
			getRequest().setAttribute("typeMap", ConfigProperties.getSysDB1("Terminal_Type",true));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		ActionContext.getContext().put("merchantList", null);
	}

	protected void dealWithTheListSpecially(List<Object> list) {
		super.dealWithTheListSpecially(list);
		Map<String, String> roleTypes = ConfigProperties
				.getRoleTypeProperties();
		List<Object> tempList = new ArrayList<Object>();
		for (Object obj : list) {
			YjPosInfo pos = (YjPosInfo) obj;
			for (TblInsInf bean : orgList) {
				if (pos.getOrgCode().equals(bean.getInsIdCd())) {
					pos.setOrgName(bean.getInsName());
				}
			}

			tempList.add(pos);
		}
		searchRsList = tempList;
	}

	@Action(value = "revTerminalPosSN", results = {
			@Result(name = SUCCESS,type="chain", location = "queryRevocationTerminalPosSN"),
			@Result(name = "error", location = "/error.jsp") 
			})
	public String revTerminalPosSN() throws Exception {
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if(null == serialnums || serialnums.equals("")){
				addActionError("sn序列号为空,不能进行撤回操作");
				return ERROR;
			}
			String [] arr = serialnums.split(",");
			List<String> revSucList = terminalService.revTerminalPosSNInfo(arr, op);
			
			String revMsg = "sn序列号撤回失败！";
			if ( null != revSucList && revSucList.size() > 0 ) {
				revMsg = "sn序列号撤回成功！撤回的SN有：" + revSucList.toString();
			} 
			getRequest().setAttribute("msg", revMsg);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		 return SUCCESS;
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (TermSnRevocationSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_SN_REVOCATION);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_SN_REVOCATION,
				searchCondition);
	}

	public Long getPsamCardStartNo() {
		return psamCardStartNo;
	}

	public void setPsamCardStartNo(Long psamCardStartNo) {
		this.psamCardStartNo = psamCardStartNo;
	}

	public Long getPsamCardEndNo() {
		return psamCardEndNo;
	}

	public void setPsamCardEndNo(Long psamCardEndNo) {
		this.psamCardEndNo = psamCardEndNo;
	}

	public Long getTotalNum() {
		return totalNum;
	}

	public void setTotalNum(Long totalNum) {
		this.totalNum = totalNum;
	}

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public TermSnRevocationSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(TermSnRevocationSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		return excelName;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

	public String getSerialnums() {
		return serialnums;
	}

	public void setSerialnums(String serialnums) {
		this.serialnums = serialnums;
	}
	
}
